package net.java.mediasearch.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public final class PictureUtil {
	
	private static final int TIMEOUT_IN_MILLISECONDS = 1000;
	private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
	
	private PictureUtil() {
		
	}
	
	public static byte[] getPictureForUrl(String url) throws IOException {
		InputStream inputStream = null;
		try {
			URLConnection urlConnection = new URL(url).openConnection();
			urlConnection.setConnectTimeout(TIMEOUT_IN_MILLISECONDS);
			urlConnection.setReadTimeout(TIMEOUT_IN_MILLISECONDS);
			urlConnection.setDoInput(true);
			urlConnection.setDoOutput(false);
			
			inputStream = urlConnection.getInputStream();
			return toByteArray(inputStream);
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}
	}
	
	private static byte[] toByteArray(InputStream inputStream) throws IOException {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        copy(inputStream, outputStream);
        return outputStream.toByteArray();
	}
	
	private static long copy(InputStream input, OutputStream output)
            throws IOException {
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        long count = 0;
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }
	
	

}
